﻿using OrderApp;
using System.DirectoryServices.ActiveDirectory;

namespace OrderUI {
    public partial class DetailsForm : Form {
        OrderDetail detail;
        MyBoolean isConfirm;
        public DetailsForm() {
            InitializeComponent();
        }

        public DetailsForm(OrderDetail detail, MyBoolean isConfirm, string text) {
            InitializeComponent();
            this.detail = detail;
            this.isConfirm = isConfirm;
            this.Text = text;
            initControl();
        }

        private void initControl() {
            detailGrid.AutoGenerateColumns = false;
            if (this.Text.Equals("修改明细")) {
                bindingSource1.DataSource = detail;
                detailGrid.DataSource = bindingSource1;
            }
            else {
                detailGrid.Rows.Add(new DataGridViewRow());
            }
        }

        private void confirmBtn_Click(object sender, EventArgs e) {
            try {
                //目前没有做到修改明细，主要问题在于不知道如何在gridview中显示原来的信息而且还能修改原来的信息
                //MessageBox.Show(detailGrid.Rows[0].Cells[0].Value.ToString());
                //var id = int.Parse(detailGrid.Rows[0].Cells[0].Value.ToString());
                //var name = detailGrid.Rows[0].Cells[1].Value.ToString();
                //var price = float.Parse(detailGrid.Rows[0].Cells[2].Value.ToString());

                //detail.Goods = new Goods(id, name, price);

                //detail.Quantity = int.Parse(detailGrid.Rows[0].Cells[3].Value.ToString());
                MessageBox.Show("操作成功");
                isConfirm.Value = true;
                this.Close();
            }
            catch (ArgumentException ex) {
                MessageBox.Show("非法数据:" + ex.Message);
            }
            catch (Exception ex) {
                MessageBox.Show("ex:" + ex.Message + ex.StackTrace);
            }
        }

        private void DetailsForm_Load(object sender, EventArgs e) {
        }

        private void DetailsForm_FormClosing(object sender, FormClosingEventArgs e) {
            if (isConfirm.Value)
                return;
            var res = MessageBox.Show("未进行确认，信息将不会保存,是否仍要退出", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.Yes) {
                isConfirm.Value = false;
            }
            else {
                e.Cancel = true;
            }
        }

        private void detailGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
            //if (!this.Text.Equals("修改明细"))
            //    return;
            switch (detailGrid.Columns[e.ColumnIndex].Name) {
                case "Id":
                    e.Value = (e.Value as Goods)?.Id; break;
                case "Price":
                    e.Value = (e.Value as Goods)?.Price; break;
                case "GoodsName":
                    e.Value = (e.Value as Goods)?.Name; break;
            }
        }
    }
}
